package cn.shadow.moulde;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import io.netty.buffer.ByteBuf;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 保存了所有的模块
 */
public class ModuleHub {
    private static final Logger logger = LoggerFactory.getLogger(ModuleHub.class);
    private final Map<Integer, String> c2sMsgMap = new HashMap<>(8192);
    private final Map<Integer, String> s2cMsgMap = new HashMap<>(8192);
    private final IModule[] modulesArray;
    private final IModule[] modules;

    private ModuleHub(List<Module> moduleList) {
        int maxModuleId = -1;

        IModule module;
        for (Iterator var4 = moduleList.iterator();
             var4.hasNext(); maxModuleId = Math.max(module.getModuleId(), maxModuleId)) {
            module = (Module) var4.next();
        }

        this.modules = moduleList.toArray(new Module[0]);
        this.modulesArray = new Module[maxModuleId + 1];
        IModule[] var9 = this.modules;
        int var11 = var9.length;

        int len;
        for (len = 0; len < var11; ++len) {
            IModule m = var9[len];
            this.modulesArray[m.getModuleId()] = m;
            this.addMessageName(m);
        }
    }

    public static ModuleHub newModuleHub(List<Module> moduleList) {
        return new ModuleHub(moduleList);
    }

    public void dispatch(int moduleId, int msgId, ByteBuf buffer, IModuleObjController controller) {
        if (moduleId >= 0 && moduleId < this.modulesArray.length) {
            IModule module = this.modulesArray[moduleId];
            if (module == null) {
                logger.error("ModuleHub.dispatch() 未知模块!{}", moduleId);
            } else {
                logger.debug("收到消息: {}-{}", moduleId, msgId);
                module.dispatch(msgId, buffer, controller);
            }
        } else {
            logger.error("ModuleHub.dispatch() 模块ID非法!{}", moduleId);
        }
    }

    private void addMessageName(IModule module) {
        Class<?> msgCls = module.getMsgCls();
        String className = msgCls.getName();
        int suffixPos = className.lastIndexOf(".");
        if (suffixPos >= 0) {
            className = className.substring(suffixPos + 1);
        }

        int moduleId = module.getModuleId();
        Field[] var6 = msgCls.getDeclaredFields();
        int var7 = var6.length;

        for (int var8 = 0; var8 < var7; ++var8) {
            Field field = var6[var8];
            field.setAccessible(true);
            if (Modifier.isStatic(field.getModifiers()) && Modifier.isFinal(field.getModifiers()) && field.getType() == Integer.TYPE) {
                try {
                    String fieldName = field.getName().toUpperCase();
                    int sequenceID;
                    int id;
                    if (fieldName.startsWith("S2C")) {
                        sequenceID = field.getInt(null);
                        id = this.short2Int(moduleId, sequenceID);
                        this.s2cMsgMap.putIfAbsent(id, className + " -> " + fieldName);
                    } else if (fieldName.startsWith("C2S")) {
                        sequenceID = field.getInt(null);
                        id = this.short2Int(moduleId, sequenceID);
                        this.c2sMsgMap.putIfAbsent(id, className + " -> " + fieldName);
                    }
                } catch (Throwable var13) {
                    throw new IllegalArgumentException("error building messages id-name map: " + moduleId, var13);
                }
            }
        }

    }

    public String getC2SMsgName(int moduleId, int msgId) {
        return this.c2sMsgMap.get(this.short2Int(moduleId, msgId));
    }

    public String getS2CMsgName(int moduleId, int msgId) {
        return this.s2cMsgMap.get(this.short2Int(moduleId, msgId));
    }

    private int short2Int(int i, int j) {
        return i << 16 | j;
    }

    public IModule getMouleById(int id) {
        return modules[id];
    }
}

